<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-11-25
 * Time: 16:45
 */

namespace app\lib\exception;

use Exception;
use think\exception\Handle;
use think\facade\Log;
use think\facade\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    public function render(Exception $e)
    {
        if($e instanceof BaseException)
        {
            //自定义异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }
        else{
            if(config('app_debug'))
            {
                return parent::render($e);
            }
            else {
                $this->code = 500;
                $this->msg = [
                    'chaojidai' => '服务器内部错误'
                ];
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }
        }
        $request = Request::instance();
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }

    private function recordErrorLog(Exception $e)
    {
        Log::init([
            'type' => 'File'
        ]);
        Log::write($e->getMessage(),'error');
    }
}